/**
 * 
 */
package com.randis.dailyplanner.managers;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.randis.dailyplanner.ServiceLocator;
import com.randis.dailyplanner.dao.ActivitiesDao;
import com.randis.dailyplanner.domain.Activity;
import com.randis.dailyplanner.domain.User;

/**
 * @author alpe
 *
 */
public class ActivitiesManager {

	private ActivitiesDao 		activityDao 		= ServiceLocator.getInstance().getActivitiesDao();
	
	private UserManager 		userManager 		= ServiceLocator.getInstance().getUserManager();

	private EmailManager 		emailManager 		= ServiceLocator.getInstance().getEmailManager();
	
    public void startChecking() {
    	
    	Date now = new Date();
    	
    	List<Activity> activities = activityDao.listNonProcessedActivities();
    	for (Activity activity : activities) {
    		if (activity.getDueDate().before(now)) {
    			processActivity(activity);
    		}
		}
    }

	private void processActivity(Activity activity) {
		String 	userId  = activity.getUserId();
		User 	user 	= userManager.getUser(userId);
		
		if (StringUtils.isEmpty(user.getMobilePhone()))
			return;
		
		String 	email 	= user.getMobilePhone() + "@sms.kyivstar.net";
		String 	text 	= "Hello";
		emailManager.send(email, text);	
		
		activity.setProcessed(true);
		saveActivity(activity);
	}

	public Activity getActivity(String id) {
		return activityDao.getActivity(id);
	}

	public void deleteActivity(String id) {
		activityDao.deleteActivity(id);		
	}

	public void saveActivity(Activity activity) {
		User user = null;
		if (!StringUtils.isBlank(activity.getUserId()))
			user = userManager.getUser(activity.getUserId());
		else
			user = userManager.getCurrentUser();		
		activityDao.saveActivity(activity, user);		
	}

	public List<Activity> list() {
		return activityDao.list();
	}
}
